package com.onlinesys.service.impl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.onlinesys.beans.UserGroup;
import com.onlinesys.database.DBManager;
import com.onlinesys.service.UserGroupService;

public class UserGroupServiceImpl implements UserGroupService {
    @Override
    public List<UserGroup> getUserGroups() throws SQLException {
        List<UserGroup> groups = new ArrayList<UserGroup>();
        String sql = "SELECT groupid, groupname, modules, rights FROM usergroups";
        Connection conn = DBManager.getDBConnection();
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
        while (rs.next()) {
            UserGroup group = new UserGroup();
            group.setGroupId(rs.getInt("groupid"));
            group.setGroupName(rs.getString("groupname"));
            group.setModules(rs.getString("modules"));
            group.setRights(rs.getInt("rights"));
            groups.add(group);
        }
        rs.close();
        stmt.close();
        conn.close();
        return groups;
    }

    @Override
    public UserGroup getUserGroupByUser(String user) throws SQLException {
        UserGroup group = new UserGroup();
        String sql = "SELECT g.groupid groupid, g.groupname groupname, g.modules modules, g.rights rights FROM usergroups g, userinfo u WHERE g.groupid = u.groupid AND u.userid = " + user;
        Connection conn = DBManager.getDBConnection();
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
        while (rs.next()) {
            group.setGroupId(rs.getInt("groupid"));
            group.setGroupName(rs.getString("groupname"));
            group.setModules(rs.getString("modules"));
            group.setRights(rs.getInt("rights"));
            break;
        } 
        rs.close();
        stmt.close();
        conn.close();
        return group;
    }
}
